<template>
  <div class="home-container">
    <!-- 引导界面 -->
    <WelcomeGuide 
      v-if="!hasCrdImported"
      @import-crd="onImportCrd"
    />
    
    <!-- 主视图 -->
    <div v-else class="main-view">
      <div class="header-bar">
        <div class="header-content">
          <div class="title-section">
            <h1>DescriptorX</h1>
            <div class="file-info">
              <el-tag type="success" size="small">{{ crdFileName }}</el-tag>
              <el-tag v-if="crdVersion" type="primary" size="small" class="version-tag">{{ crdVersion }}</el-tag>
            </div>
          </div>
          <div class="actions-section">
            <el-button 
              type="info" 
              size="default" 
              @click="showCrdDialog"
              class="view-crd-btn"
            >
              <el-icon><View /></el-icon>
              查看 CRD
            </el-button>
            <el-button 
              type="warning" 
              size="default" 
              @click="resetWorkspace"
              class="reset-btn"
            >
              <el-icon><Refresh /></el-icon>
              重新开始
            </el-button>
          </div>
        </div>
      </div>

      <el-container class="content-container">
        <el-main>
          <el-row :gutter="20" class="main-row">
            <el-col :span="12">
              <div class="left-panel">
                <div class="sample-editor-section">
                  <TextSample 
                    :crd-text="crdText"
                    @sample-change="onSampleChange"
                    @apply-to-fields="onApplyToFields"
                  />
                </div>
                <div class="descriptor-editor-section">
                  <TextDescriptor 
                    :tree-data="treeData" 
                    @descriptors-change="onDescriptorsChange"
                    @update-fields="onUpdateFields"
                    :should-sync="shouldSyncToDescriptor"
                  />
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <FieldController 
                :tree-data="treeData" 
                @update-fields="onUpdateFields"
                @sync-to-descriptor="onSyncToDescriptor"
              />
            </el-col>
          </el-row>
        </el-main>
      </el-container>
    </div>

    <!-- CRD 查看弹窗 -->
    <CrdViewDialog 
      v-model="crdDialogVisible"
      :crd-text="crdText"
      :file-name="crdFileName"
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { View, Refresh } from '@element-plus/icons-vue'
import WelcomeGuide from '../components/WelcomeGuide.vue'
import CrdViewDialog from '../components/CrdViewDialog.vue'
import TextSample from '../components/TextSample.vue'
import TextDescriptor from '../components/TextDescriptor.vue'
import FieldController from '../components/FieldController.vue'
import { invoke } from '@tauri-apps/api/core'
import { ElMessage, ElMessageBox } from 'element-plus'

const treeData = ref<any[]>([])
const crdText = ref('')
const crdFileName = ref('')
const crdVersion = ref('')
const sampleText = ref('')
const hasCrdImported = ref(false)
const crdDialogVisible = ref(false)
const shouldSyncToDescriptor = ref(0) // 使用数字作为触发器

async function onImportCrd(text: string, fileName: string) {
  try {
    crdText.value = text
    crdFileName.value = fileName
    
    // 解析CRD
    const result = await invoke('load_crd_from_file', { crdText: text }) as { tree_data: any[], selected_version?: string }
    treeData.value = result.tree_data
    crdVersion.value = result.selected_version || ''
    hasCrdImported.value = true
    
    console.log('CRD导入成功，解析出字段:', result.tree_data, '选择版本:', result.selected_version)
  } catch (e) {
    ElMessage.error('CRD解析失败，请检查文件格式')
    console.error('CRD解析失败:', e)
  }
}

function showCrdDialog() {
  crdDialogVisible.value = true
}

async function resetWorkspace() {
  try {
    await ElMessageBox.confirm(
      '确定要重新开始吗？这将清空当前所有工作内容。',
      '确认重置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 重置所有状态
    treeData.value = []
    crdText.value = ''
    crdFileName.value = ''
    crdVersion.value = ''
    sampleText.value = ''
    hasCrdImported.value = false
    crdDialogVisible.value = false
    
  } catch {
    // 用户取消操作
  }
}

function onSampleChange(text: string) {
  sampleText.value = text
  console.log('Sample changed:', text)
}

function onApplyToFields(updatedTreeData: any[]) {
  console.log('Applying sample to fields:', updatedTreeData)
  treeData.value = updatedTreeData
  // 触发同步到Descriptor
  onSyncToDescriptor()
}

function onDescriptorsChange(descriptors: any) {
  console.log('Descriptors changed:', descriptors)
}

function onUpdateFields(updatedTreeData: any[]) {
  console.log('HomeView: Updating fields with:', updatedTreeData)
  // 直接使用Rust后端处理好的数据
  treeData.value = updatedTreeData
  console.log('HomeView: treeData updated, new value:', treeData.value)
}

function onSyncToDescriptor() {
  console.log('HomeView: Sync to descriptor triggered')
  // 增加计数器来触发TextDescriptor的同步
  shouldSyncToDescriptor.value++
}
</script>

<style lang="scss" scoped>
.home-container {
  height: 100vh;
  overflow: hidden; // 防止全局滚动
  
  .main-view {
    height: 100vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .header-bar {
      flex-shrink: 0;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-bottom: 1px solid #e1e8ed;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

      .header-content {
        padding: 20px 24px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        max-width: 1400px;
        margin: 0 auto;

        .title-section {
          display: flex;
          align-items: center;
          gap: 16px;

          h1 {
            font-size: 28px;
            font-weight: 700;
            color: #ffffff;
            margin: 0;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          }

          .file-info {
            display: flex;
            align-items: center;
            gap: 8px;

            .el-tag {
              background: rgba(255, 255, 255, 0.9);
              color: #667eea;
              border: none;
              font-weight: 600;
            }

            .version-tag {
              background: rgba(255, 255, 255, 0.9);
              color: #764ba2;
              border: none;
              font-weight: 600;
            }
          }
        }

        .actions-section {
          display: flex;
          gap: 16px;

          .view-crd-btn, .reset-btn {
            padding: 10px 20px;
            font-weight: 600;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
            transition: all 0.3s ease;

            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
            }
          }

          .view-crd-btn {
            background: #17a2b8;
            border-color: #17a2b8;
            color: white;
          }

          .reset-btn {
            background: #ffc107;
            border-color: #ffc107;
            color: #212529;
          }
        }
      }
    }

    .content-container {
      flex: 1;
      min-height: 0; // 重要：允许收缩
      padding: 16px;
      overflow: hidden;

      .el-main {
        padding: 0;
        height: 100%;
        overflow: hidden;

        .main-row {
          height: 100%;

          .el-col {
            height: 100%;
          }
        }
      }
    }
  }
  
  .left-panel {
    height: 100%;
    display: flex;
    flex-direction: column;
    gap: 16px;
    overflow: hidden;
    
    .sample-editor-section {
      flex: 1;
      min-height: 0; // 允许收缩
    }
    
    .descriptor-editor-section {
      flex: 1;
      min-height: 0; // 允许收缩
    }
  }
}
</style> 